package cn.zysuyuan.item.service.impl;

import cn.zysuyuan.common.entity.Constant;
import cn.zysuyuan.common.entity.PageResult;
import cn.zysuyuan.common.utils.BeanMapUtils;
import cn.zysuyuan.common.utils.UUIDUtil;
import cn.zysuyuan.item.entity.Role;
import cn.zysuyuan.item.entity.RoleAndPermission;
import cn.zysuyuan.item.mapper.RoleMapper;
import cn.zysuyuan.item.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author flypig
 * @version 1.0
 * @date 2020-03-17 18:37
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public int save(Role role) {
        role.setId(UUIDUtil.uuid());
        role.setfCreateTime(new Date());
        return roleMapper.save(role);
    }

    @Override
    public int update(Role role) {

        return roleMapper.update(role);
    }

    @Override
    public int assignPerms(Map<String, Object> map) {
        String roleId = (String) map.get("roleId");
        List<String> ids = (List<String>)map.get("ids");
        // 保存角色权限之前，将本角色拥有的所有权限全部删除
        roleMapper.delete(roleId);
        int inserts = 0;
        List<RoleAndPermission> permlist = new ArrayList<RoleAndPermission>();
        if (ids != null && ids.size() > 0) {
            for (int i = 0; i < ids.size(); i++) {
                RoleAndPermission rPerm = new RoleAndPermission();
                rPerm.setRoleId(roleId);
                rPerm.setPermissionId(ids.get(i));
                permlist.add(rPerm);
            }
            inserts = roleMapper.insert(permlist);
        }
        return inserts;
    }

    @Override
    public int delete(String id) {
        roleMapper.delete(id);
        roleMapper.deleteByRoleId(id);
        return roleMapper.deleteById(id);
    }

    @Override
    public Map<String, Object> findById(String id) {
        Role role = roleMapper.findById(id);
        List<String> list = roleMapper.findPermById(id);
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> maps = new HashMap<>();
        map = BeanMapUtils.beanToMap(role);

        map.put("permIds",list);
        maps.put("data",map);
        return maps;
    }

    @Override
    public PageResult<Role> selectList(Map<String, Object> map) {
        List<Role> list = roleMapper.selectList(map);
        return new PageResult<>(list);
    }

    @Override
    public List<Role> findAll() {
        List<Role> list = roleMapper.findAll();
        return list;
    }
}
